package org.ws.task.common;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public final class IPUtils {

    private static Logger log = LoggerFactory.getLogger(IPUtils.class.getName());

    private IPUtils(){}

    /**
     * 获取本机IP
     * @return
     */
    public static String getIP(){
        try {
            return getIpAdd();
        } catch (SocketException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    /**
     * 根据网卡获得IP地址
     * @return
     * @throws SocketException
     */
    public static String getIpAdd() throws SocketException{
        String ip="";
        int minIp = Integer.MAX_VALUE;
        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
            NetworkInterface networkInterface = en.nextElement();
            String name = networkInterface.getName();
            if (!name.contains("docker") && !name.contains("lo")) {
                for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    //获得IP
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        String ipAddress = inetAddress.getHostAddress();
                        if(StringUtils.isBlank(ipAddress)){
                            continue;
                        }
                        if (!ipAddress.contains(":") && !ipAddress.contains("0:0:") && !ipAddress.contains("fe80")) {
                            int intIP = Integer.parseInt(ipAddress.replaceAll("\\.",""));
                            // 多个IP取最小的
                            if(!"127.0.0.1".equals(ip) && minIp>intIP){
                                ip = ipAddress;
                                minIp = intIP;
                            }
                        }
                    }
                }
            }
        }
        return ip;
    }
}
